// roleModel.js
const pool = require("@/db"); // 引入连接池
const table = require("@/db/table"); // 引入连接池

// 根据ID查询角色
async function getRoleById({ id }) {
  return await pool
    .select("*")
    .from(table.ROLE)
    .where("id", id, "eq", "ifHave")
    .queryRow();
}

// 添加角色
async function addRole(role) {
  const result = await pool
    .insert(table.ROLE, {
      name: role.name,
      description: role.description,
      created_at: new Date(),
      updated_at: new Date(),
    })
    .execute();
  return result.insertId;
}

// 删除角色
async function deleteRole(id) {
  const result = await pool.delete(table.ROLE).where("id", id).execute();
  return result.affectedRows > 0;
}

// 更新角色
async function updateRole(id, role) {
  const result = await pool
    .update(table.ROLE, { name: role.name, description: role.description })
    .where("id", id)
    .execute();
  return result.affectedRows > 0;
}

// 查询角色列表
async function getRoles({ page_index = 1, page_size = 20 }) {
  return await pool
    .select("*")
    .from(table.ROLE)
    .queryListWithPaging(page_index, page_size);
}

// 查询角色下菜单
async function getRoleMenus(id) {
  return await pool
    .select("m.*")
    .from(`${table.ROLE_MENU} as mr`)
    .join(`left join ${table.MENU} as m on m.id = mr.menu_id`)
    .where("mr.role_id", id)
    .orderby("sort", "desc")
    .queryList();
}

module.exports = {
  getRoleById,
  addRole,
  deleteRole,
  updateRole,
  getRoles,
  getRoleMenus,
};
